package com.aidex.biz.service.impl;

import com.aidex.biz.domain.PushRule;
import com.aidex.biz.domain.PushRuleUser;
import com.aidex.biz.domain.TempShareRule;
import com.aidex.biz.mapper.PushRuleMapper;
import com.aidex.biz.service.PushRuleService;
import com.aidex.biz.service.PushRuleUserService;
import com.aidex.biz.service.TempShareRuleService;
import com.aidex.biz.service.TempShareService;
import com.aidex.common.annotation.DataScope;
import com.aidex.common.core.page.PageDomain;
import com.aidex.common.core.service.BaseServiceImpl;
import com.aidex.common.utils.NumberUtils;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.sql.SqlUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 分配规则Service业务层处理
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2025-03-11
 */
@Service
@Transactional(readOnly = true)
public class PushRuleServiceImpl extends BaseServiceImpl<PushRuleMapper, PushRule> implements PushRuleService {
    private static final Logger log = LoggerFactory.getLogger(PushRuleServiceImpl.class);


    @Autowired
    private PushRuleUserService pushRuleUserService;
    @Autowired
    private TempShareRuleService tempShareRuleService;
    @Autowired
    private TempShareService tempShareService;
    /**
     * 获取单条数据
     *
     * @param pushRule 分配规则
     * @return 分配规则
     */
    @Override
    public PushRule get(PushRule pushRule) {
        PushRule dto = super.get(pushRule);
        return this.addPushUsersInfo(dto);
    }

    /**
     * 获取单条数据
     *
     * @param id 分配规则id
     * @return 分配规则
     */
    @Override
    public PushRule get(String id) {
        PushRule dto = super.get(id);
        return this.addPushUsersInfo(dto);
    }

    /**
     * 查询按人员分配分配规则列表
     *
     * @param pushRule 分配规则
     * @return 分配规则
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<PushRule> findRuleListByUser(PushRule pushRule) {

        return mapper.findRuleListByUser(pushRule);
    }


    /**
     * 查询分配规则列表
     *
     * @param pushRule 分配规则
     * @return 分配规则
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<PushRule> findList(PushRule pushRule) {
        return super.findList(pushRule);
    }

    /**
     * 分页查询分配规则列表
     *
     * @param pushRule 分配规则
     * @return 分配规则
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<PushRule> findPage(PushRule pushRule) {
        PageDomain page = pushRule.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        //按人员分配
        if ("1".equals(pushRule.getRuleSet())) {
            if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
                pushRule.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
            }
            List<PushRule> list = findRuleListByUser(pushRule);
            //添加分配人员信息
            if (null != list && !list.isEmpty()) {
                List<PushRuleUser> pushUserList = pushRuleUserService.findPushUserListByRuleIds(list);
                Map<String, List<PushRuleUser>> pushUserMap = pushUserList.stream().collect(Collectors.groupingBy(PushRuleUser::getRuleId));
                for (PushRule rule : list) {
                    rule.setRuleUsers(pushUserMap.get(rule.getId()));
                }
            }
            return new PageInfo(list);
        } else {
            return new PageInfo(findList(pushRule));
        }
    }

    /**
     * 保存分配规则
     *
     * @param pushRule
     * @return 结果
     */
    @Override
    public boolean save(PushRule pushRule) {
        // 新增
        if ("1".equals(pushRule.getRuleSet())) {
            if (pushRule.getId().equals(pushRule.getUserId())) {
                pushRule.setId(UUID.randomUUID().toString());
                pushRule.setIsNewRecord();
            }
        }

        boolean isSaved = super.save(pushRule);
        List<PushRuleUser> pushRuleUsers = pushRule.getRuleUsers();

        if (isSaved) {
            if (null != pushRuleUsers && !pushRuleUsers.isEmpty()) {
                // 自定义规则
                if ("2".equals(pushRule.getRuleSet())) {
                    for (PushRuleUser pushRuleUser : pushRuleUsers) {
                        if (StringUtils.isNull(pushRuleUser.getRuleId())) {
                            pushRuleUser.setIsNewRecord();
                            pushRuleUser.setStatus("0");
                            pushRuleUser.setRuleId(pushRule.getId());
                            pushRuleUser.setSharedCount(0);
                        }
                        pushRuleUserService.save(pushRuleUser);
                    }
                }// 按人员分配
                else {
                    PushRuleUser pushRuleUserparam = new PushRuleUser();
                    pushRuleUserparam.setRuleId(pushRule.getId());
                    List<PushRuleUser> pushRuleUsersExist = pushRuleUserService.findList(pushRuleUserparam);
                    for (PushRuleUser pushRuleUser : pushRuleUsers) {
                        PushRuleUser param = new PushRuleUser();
                        param.setRuleId(pushRule.getId());
                        //param.setCity(pushRuleUser.getCity());
                        param.setUserId(pushRuleUser.getUserId());
                        param.setLaiyuan(pushRuleUser.getLaiyuan());
                        List<PushRuleUser> pushRuleUserListExist = pushRuleUserService.findList(param);
                        if (null != pushRuleUserListExist && !pushRuleUserListExist.isEmpty()) {
                            PushRuleUser pushRuleUserExist = pushRuleUserListExist.get(0);
                            pushRuleUsersExist.remove(pushRuleUserExist);
                            pushRuleUserExist.setIsEnable(pushRuleUser.getIsEnable());
                            pushRuleUserExist.setMaxCount(pushRuleUser.getMaxCount());
                            pushRuleUserExist.setCity(pushRuleUser.getCity());
                            pushRuleUserService.save(pushRuleUserExist);

                        } else {
                            pushRuleUser.setIsNewRecord();
                            pushRuleUser.setStatus("0");
                            pushRuleUser.setRuleId(pushRule.getId());
                            pushRuleUser.setSharedCount(0);
                            pushRuleUserService.save(pushRuleUser);
                        }
                    }
                    // 如果数据库里还有剩余 说明需要删除
                    if (!pushRuleUsersExist.isEmpty()) {
                        String[] removedUserIds = pushRuleUsersExist.stream()
                                .map(PushRuleUser::getId)
                                .toArray(String[]::new);
                        pushRuleUserService.deletePushRuleUserByIds(removedUserIds);
                    }
                }

            } else {
                String[] ids = new String[]{pushRule.getId()};
                pushRuleUserService.deletePushRuleUserByRuleIds(ids);
            }
        }
        return isSaved;
    }


    /**
     * 删除分配规则信息
     *
     * @param pushRule
     * @return 结果
     */
    @Override
    public boolean remove(PushRule pushRule) {
        return super.remove(pushRule);
    }

    /**
     * 批量删除分配规则
     *
     * @param ids 需要删除的分配规则ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deletePushRuleByIds(String[] ids) {
        int delCount = mapper.deletePushRuleByIds(ids);
        if (delCount > 0) {
            pushRuleUserService.deletePushRuleUserByRuleIds(ids);
        }
        return delCount;
    }

    /**
     * 获取最大编号
     *
     * @param pushRule 分配规则
     * @return 结果
     */
    @Override
    public int findMaxSort(PushRule pushRule) {
        return NumberUtils.nextOrder(mapper.findMaxSort(pushRule));
    }

    private PushRule addPushUsersInfo(PushRule pushRule) {
        if (null != pushRule) {
            PushRuleUser pushRuleUser = new PushRuleUser();
            pushRuleUser.setRuleId(pushRule.getId());


            if ("1".equals(pushRule.getRuleSet())) {
                pushRule.setRuleUsers(pushRuleUserService.findList(pushRuleUser));
            } else {
                if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
                    pushRuleUser.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
                }
                pushRule.setRuleUsers(pushRuleUserService.findUserJoinRuleList(pushRuleUser));
            }

        }
        return pushRule;
    }

    /**
     * 判断规则是否唯一
     *
     * @param pushRule
     * @return
     */
    @Override
    public PushRule findExist(PushRule pushRule) {

//        if (null != pushRule) {
//            String cityStr = pushRule.getRuleCities();
//            String laiyuanStr = pushRule.getLaiyuan();
//            if (null != cityStr && null != laiyuanStr) {
//                cityStr = cityStr.replace("[", "").replace("]", "").replace("\"", "");
//                laiyuanStr = laiyuanStr.replace("[", "").replace("]", "").replace("\"", "");
//                // 按逗号分割成数组
//                String[] cityArray = cityStr.split(",");
//                String[] laiyuanArray = laiyuanStr.split(",");
//                PushRule pushRuleParam = new PushRule();
//                pushRuleParam.setId(pushRule.getId());
//                //pushRuleParam.setRuleLogic(pushRule.getRuleLogic());
//                pushRuleParam.setRuleType(pushRule.getRuleType());
//                for (String city : cityArray) {
//                    for (String laiyuan : laiyuanArray) {
//                        pushRuleParam.setRuleCities(city);
//                        pushRuleParam.setLaiyuan(laiyuan);
//                        PushRule pushRuleExist = mapper.findExist(pushRuleParam);
//                        if (null != pushRuleExist) {
//                            // 把规则冲突的城市、来源返给前端
//                            pushRuleExist.setRuleCities(city);
//                            pushRuleExist.setLaiyuan(laiyuan);
//                            return pushRuleExist;
//                        }
//                    }
//                }
//            }
//        }
        return null;
    }

    /**
     * 带临时表查询规则
     * @param pushRule
     * @return
     */
    private List<PushRule> findRulesByLaiyuanCityWithTemp(PushRule pushRule) {
        pushRule.setWithTemp("true");
        return mapper.findRulesByLaiyuanCity(pushRule);
    }

    /**
     * 查询所有规则
     * @param pushRule
     * @return
     */
    private List<PushRule> findRulesByLaiyuanCityWithoutTemp(PushRule pushRule) {
        pushRule.setWithTemp(null);
        return mapper.findRulesByLaiyuanCity(pushRule);
    }

    @Override
    public PushRule getPushRule(PushRule pushRuleParam) {
        List<PushRule> pushRuleList = this.findRulesByLaiyuanCityWithTemp(pushRuleParam);
        PushRule pushRule = null;
        if (null != pushRuleList && !pushRuleList.isEmpty()) {
            pushRule = pushRuleList.get(0);
        } else {
            //没有可分配的规则了  表示符合条件的规则已经用完了一轮 需要重置临时表 从第一个规则再分配
            List<PushRule> allPushRuleList = this.findRulesByLaiyuanCityWithoutTemp(pushRuleParam);
            if (!allPushRuleList.isEmpty()) {
               for(PushRule deletePule :allPushRuleList){
                   TempShareRule tempShareRule=new TempShareRule();
                   tempShareRule.setRuleId(deletePule.getId());
                   tempShareRule.setLaiyuan(pushRuleParam.getLaiyuan());
                   tempShareRuleService.deleteTempShareRuleByRuleIdLaiyuan(tempShareRule);
                   //按人员分配 一轮规则分完 也就是这一轮人员分完了 需要清除人员临时表
                   if("1".equals(deletePule.getRuleSet())){
                       PushRuleUser pushRuleUser=new PushRuleUser();
                       pushRuleUser.setRuleId(deletePule.getId());
                       pushRuleUser.setLaiyuan(pushRuleParam.getLaiyuan());
                       pushRuleUser.setCity(pushRuleParam.getRuleCities());
                       List<PushRuleUser> pushRuleUserList = pushRuleUserService.findList(pushRuleUser);
                       if (!pushRuleUserList.isEmpty()) {
                           String[] ids = new String[pushRuleUserList.size()];
                           for (int i = 0; i < pushRuleUserList.size(); i++) {
                               ids[i] = pushRuleUserList.get(i).getId();
                           }
                           tempShareService.deleteAllByUserRuleIds(ids);
                       }
                   }
               }
            }
            // 重新取规则
            pushRuleList = this.findRulesByLaiyuanCityWithTemp(pushRuleParam);
            if (null != pushRuleList && !pushRuleList.isEmpty()) {
                pushRule = pushRuleList.get(0);
            }
        }
        return pushRule;
    }
}













